//index.js
const utils = require("../../utils/utils.js");
const biz = require("../../utils/bizUtils.js");
const listUtil = require("../../utils/listUtil.js");
const session = require("../../utils/session.js");
const toast = require("../../utils/toasts.js");
const wxm = require("../../utils/wechat_modules.js");
const com = require("../../utils/commonRequest.js");
const cache = require("../../utils/cache.js");

import {
  order_pay,
  req
} from "../../utils/api.js";

//获取应用实例
const app = getApp()
const globalData = app.globalData;

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    list: [],
    hidden: true,
    scrollTop: 0,
    scrollHeight: 0,
    title: '',
    keyword: null,
    catId: null,
    orderRule: 'HOT',
    waiting: true,
    share_modal: false,
    noMore: false,
    banners: ['https://img.lingxing.site/jx/small_banner_jx1.png'],
    isIphoneX: globalData.isIphoneX,
    curIndex: 0,
    pageNo: 1,
    rightCount: 0,
    wrongCount: 0,
    tabIndex: 1,
    inTest: false,
    items: [{
        "iconPath": '/images/tabbar_back_icon2.png',
        type: 'back'
      },
      {
        "click": "pre",
        "text": "上一题",
        "selectedIconPath": "/images/tabbar_pre_icon.png",
        "iconPath": "/images/tabbar_pre_icon.png"
      },
      {
        "click": "next",
        "text": "下一题",
        "selectedIconPath": "/images/tabbar_next_icon.png",
        "iconPath": "/images/tabbar_next_icon.png"
      },
      {
        "click": "fav",
        "text": "收藏",
        "selectedIconPath": "/images/tabbar_card_selected_icon.png",
        "iconPath": "/images/tabbar_card_icon.png"
      },
      {
        "text": "提交",
        "click": "submit",
        "selectedIconPath": "/images/tabbar_submit_icon.png",
        "iconPath": "/images/tabbar_submit_icon.png"
      }
    ]
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function(options) {
    var that = this;

    if (options) {
      if (options.id) {
        this.setData({
          id: options.id
        });
      }

      if (options.from) {
        this.setData({
          from: options.from
        })
      }


      if (options.salesId) {
        this.setData({
          salesId: options.salesId
        })
        if (options.salesName) {}
      }

      if (options.index) {
        this.setData({
          index: options.index
        });
      }

      if (options.cateid) {
        this.setData({
          cateid: options.cateid
        });
      }

      if (options.type) {
        this.setData({
          type: options.type,
        })
        if (options.type == 'wrong') {
          wx.setNavigationBarTitle({
            title: '错题练习'
          })
        } else if (options.type == 'fav') {
          wx.setNavigationBarTitle({
            title: '收藏题目'
          })
        } else if (options.type == 'test') {
          wx.setNavigationBarTitle({
            title: '模拟考试'
          });
          com.laterRun(this, 300, this.showTest);
        } else if (options.type == 'ran') {
          wx.setNavigationBarTitle({
            title: '随机练习',
          });
          com.laterRun(this, 300, this.showRan);
        } else if (options.type == 'chap') {
          wx.setNavigationBarTitle({
            title: '章节练习'
          });
          com.laterRun(this, 300, this.showChap);
        }
      }
    }

    session.login(this.refreshMe);
  },
  showRan: function() {
    var that = this;
    var counts = [10, 30, 50, 100, 200];
    wx.showActionSheet({
      itemList: ['10道题', '30道题', '50道题', '100道题', '200道题'],
      success: function(e) {
        var index = e.tapIndex;
        that.setData({
          ran: counts[index]
        })
        toast.showLoading();
        that.getData();
      },
      fail: function(e) {
        wx.navigateBack({

        })
      }
    })
  },
  showChap: function() {
    var that = this;
    var itemList = ['道路交通安全法律、法规和规章（616题）', '道路交通信号（333题）', '安全行车、文明驾驶基础知识（241题）', '机动车驾驶操作相关基础知识（135题）'];
    if (this.data.cateid == 4) {
      itemList = ['违法行为综合判断与案例分析（39题）', '安全行车常识（331题）', '常见交通标志、标线和交警手势信号辨识（215题）', '驾驶职业道德和文明驾驶常识（169题）', '恶劣气候和复杂道路条件下驾驶常识（221题）', '紧急情况下避险常识（109题）'];
    }

    wx.showActionSheet({
      itemList: itemList,
      success: function(e) {
        var index = e.tapIndex;
        that.setData({
          chap: index + 1
        })
        toast.showLoading();
        that.getData();
      },
      fail: function(e) {
        wx.navigateBack({

        })
      }
    });
  },
  showTest: function() {
    var that = this;
    wx.showActionSheet({
      itemList: ['开始考试'],
      success: function(e) {
        var index = e.tapIndex;
        if (index == 0) {
          that.addTest();
        } else if (index == 1) {
          that.history();
        }
      },
      fail: function(e) {
        wx.navigateBack({

        })
      }
    })
  },
  refreshMe: function(usr) {
    this.setData({
      user: usr
    });

    if (this.data.type != 'test' && this.data.type != 'ran' && this.data.type != 'chap') {
      toast.showLoading();
      this.getData();
    }
  },
  onShow: function() {},
  getData() {
    var pageNo = this.data.pageNo;
    var cateid = this.data.cateid;
    var pageSize = 10;
    var list = this.data.list;

    var param = {
      pageNo,
      pageSize,
      cateid
    };


    if (this.data.chap) {
      param.chapterid = this.data.chap;
    }

    var api = '/jxq/query';
    if (this.data.type == 'wrong') {
      api = '/jxq/queryWrong';
    } else if (this.data.type == 'fav') {
      api = '/jxq/queryFav';
    } else if (this.data.type == 'test') {
      api = '/jxq/getTestItems';
      param = {
        id: this.data.obj.id
      };
    } else if (this.data.type == 'ran') {
      api = '/jxq/ran';
      param = {
        count: this.data.ran,
        cateid
      };
    }

    var that = this;
    req(api, param).then(res => {
      // console.log(res);
      if (res.success) {
        var clist = res.result;
        var totalRecords = clist.length;
        var pageCount = 1;
        if (this.data.type != 'test' && this.data.type != 'ran') {
          totalRecords = res.result.page.totalRecords;
          pageCount = res.result.page.pageCount;
          clist = res.result.list;
        }

        if (!clist.length) {
          if (that.data.type == 'fav') {
            wxm.showModal({
              title: '暂无收藏',
              content: '您可以点击题目下方的收藏按钮来收藏题目',
              hideCancel: true,
              confirmText: '确定',
              isIt: (true)
            }).then(() => {
              wx.navigateBack({

              })
              return;
            }).catch(() => {});
          } else if (that.data.type == 'wrong') {
            wxm.showModal({
              title: '暂无错题',
              content: '答错的题目会显示在这里',
              hideCancel: true,
              confirmText: '确定',
              isIt: (true)
            }).then(() => {
              wx.navigateBack({

              })
              return;
            }).catch(() => { });
          }
        }

        if (clist) {
          for (var i = 0; i < clist.length; i++) {
            var item = clist[i];
            item.ans = [];
            item.showResult = false;
            item.answertrueStr = biz.answerStr(item.answertrue, item.type);
            if (item.type == 1) {
              item.ans.push({
                anIndex: 'A',
                an: '正确',
                select: false
              });
              item.ans.push({
                anIndex: 'B',
                an: '错误',
                select: false
              });
            } else {
              item.ans.push({
                anIndex: 'A',
                an: item.an1,
                select: false
              });
              item.ans.push({
                anIndex: 'B',
                an: item.an2,
                select: false
              });
              item.ans.push({
                anIndex: 'C',
                an: item.an3,
                select: false
              });
              item.ans.push({
                anIndex: 'D',
                an: item.an4,
                select: false
              });
            }

            list.push(item);
          }
        }

        that.setData({
          list,
          pageCount,
          totalRecords
        });
        that.setCur();
      } else {
        toast.show(res.errorMsg);
      }
    });
  },
  pushFormSubmit: function(e) {
    console.log(e);
    console.log("formId:" + e.detail.formId);
    com.saveFormId(e);
  },
  back: function() {
    wxm.back(this);
  },
  next: function() {
    var curIndex = this.data.curIndex;
    var totalRecords = this.data.totalRecords;

    if (curIndex >= totalRecords - 1) {
      return toast.show('后面没有了');
    }

    curIndex = curIndex + 1;

    this.setData({
      curIndex
    })

    this.setCur();

    var pageNo = this.data.pageNo;
    var pageCount = this.data.pageCount;
    if (pageNo >= pageCount) {
      return;
    }

    if (this.data.type == 'test' || this.data.type == 'ran') {
      return;
    }

    var list = this.data.list;
    if (curIndex + 5 >= list.length) {
      pageNo = pageNo + 1;
      this.setData({
        pageNo
      });
      this.getData();
    }
  },
  pre: function() {
    var curIndex = this.data.curIndex;
    var totalRecords = this.data.totalRecords;

    if (curIndex <= 0) {
      return toast.show('已经是第一题');
    }

    curIndex = curIndex - 1;

    this.setData({
      curIndex
    })

    this.setCur();
  },
  setCur: function() {
    var curIndex = this.data.curIndex;
    var list = this.data.list;
    var cur = list[curIndex];

    this.setData({
      cur,
      showTip: cur.showResult
    })

    this.setFav(cur.isFav);
  },
  select: function(e) {
    var index = e.currentTarget.dataset.index;
    var cur = this.data.cur;
    if (cur.showResult) {
      return;
    }
    var showTip = false;

    // 测试或者多选不立即展示答案
    if (this.data.type != 'test' && cur.type != 3) {
      cur.showResult = true;
      showTip = true;
    }

    cur.answer = (index + 1);

    var right = parseInt(cur.answertrue);
    var rightCount = this.data.rightCount;
    var wrongCount = this.data.wrongCount;

    for (var i = 0; i < cur.ans.length; i++) {
      // 多选情况
      if (cur.type == 3) {
        if (index == i) {
          cur.ans[i].select = !cur.ans[i].select;
        }
      } else {
        cur.ans[i].select = (index == i);
      }
    }

    if (cur.type != 3) {
      if (index + 1 == right) {
        var an = cur.ans[index];
        an.showResult = true;
        an.right = true;

        rightCount = rightCount + 1;
        cur.right = true;
      } else {
        var an = cur.ans[index];
        an.showResult = true;
        an.right = false;

        var anr = cur.ans[right - 1];
        anr.showResult = true;
        anr.right = true;

        wrongCount = wrongCount + 1;
      }
    }

    var list = this.data.list;
    var curIndex = this.data.curIndex;
    list[curIndex] = cur;

    this.setData({
      cur,
      list,
      showTip: showTip,
      rightCount,
      wrongCount
    })

    if (cur.type != 3) {
      this.addRecord(cur.id, index + 1);
    }
  },
  showTip: function() {
    var showTip = this.data.showTip;
    this.setData({
      showTip: !showTip
    })
  },
  addRecord(jxQId, select) {
    var that = this;
    req('/jxq/addRecord', {
      jxQId,
      answer: select
    }).then(res => {});
  },
  addTest: function() {
    var cateid = this.data.cateid;
    var api = '/jxq/addTest';
    var that = this;


    toast.showLoading();
    req(api, {
      cateid,
    }).then(res => {
      // console.log(res);
      if (res.success) {
        var obj = res.result;
        that.setData({
          obj,
          inTest: true
        })

        that.setData({
          downSec: 60 * 45,
          downTime: '45:00',
          runCountDown: true
        })

        that.startTimeout();

        if (obj.id) {
          that.getData();
        }

      } else {
        toast.show(res.errorMsg);
      }
    });
  },
  startTimeout: function() {
    this.countDown();
  },
  fav: function() {
    var cur = this.data.cur;
    var isFav = cur.isFav;
    isFav = !isFav;
    cur.isFav = isFav;

    var api = '/jxq/fav';
    var that = this;

    if (!isFav) {
      api = '/jxq/rmfav';
    }

    toast.showLoading();
    req(api, {
      id: cur.id
    }).then(res => {
      // console.log(res);
      if (res.success) {
        that.setFav(isFav);

        var list = that.data.list;
        var curIndex = that.data.curIndex;
        list[curIndex] = cur;
        that.setData({
          cur,
          list
        })

      } else {
        toast.show(res.errorMsg);
      }
    });
  },
  setFav: function(isFav) {
    var items = this.data.items;
    items[3].text = isFav ? '已收藏' : '收藏';
    items[3].selectedIconPath = isFav ? '/images/tabbar_card_selected_icon.png' : '/images/tabbar_card_icon.png';
    items[3].iconPath = isFav ? '/images/tabbar_card_selected_icon.png' : '/images/tabbar_card_icon.png';
    this.setData({
      items
    })
  },
  submit: function() {
    if (this.data.type == 'test') {
      this.submitTest();
      return;
    }

    var content = '正确数' + this.data.rightCount + '，错误数' + this.data.wrongCount;
    wxm.showModal({
      title: '成绩单',
      content: content,
      hideCancel: false,
      confirmText: '退出',
      cancelText: '继续作答',
      isIt: (true)
    }).then(() => {
      wx.navigateBack({

      })
      return;
    }).catch(() => {});
    return;
  },
  submitTest: function(timeout) {
    var that = this;
    if (this.data.rightCount + this.data.wrongCount < this.data.list.length) {
      // return toast.show('题目还没有做完');
    }

    var title = '确认提交吗';
    var content = '提交后将不能修改';
    var hideCancel = false;
    var confirmText = '确认';
    if (timeout) {
      title = '答题时间到';
      content = '倒计时已经结束';
      hideCancel = true;
    }

    wxm.showModal({
      title: title,
      content: content,
      hideCancel: hideCancel,
      confirmText: confirmText,
      cancelText: '继续作答',
      isIt: (true)
    }).then(() => {
      that.setData({
        runCountDown: false
      })

      that.subMs();

      that.doSubmitTest();
      that.setData({
        wrongCount: (that.data.list.length - that.data.rightCount)
      })
      var time = that.calDownTime((60 * 45 - that.data.downSec), true);

      var content = '用时' + time + '，分数' + this.data.rightCount + '，正确数' + this.data.rightCount + '，错误数' + this.data.wrongCount;
      var title = '恭喜你合格了';
      if (this.data.rightCount < 90) {
        title = '很遗憾没合格';
      }
      wxm.showModal({
        title: title,
        content: content,
        hideCancel: false,
        confirmText: '查看试卷',
        cancelText: '直接退出',
        isIt: (true)
      }).then(() => {
        that.viewResult();
      }).catch(() => {
        wx.navigateBack({

        })
        return;
      });
      return;
    }).catch(() => {});
  },
  countDown: function() {
    if (!this.data.runCountDown) {
      return;
    }

    var downSec = this.data.downSec;
    downSec = downSec - 1;

    if (downSec < 0) {
      this.submitTest(true);
      return;
    }

    var downTime = this.calDownTime(downSec);

    this.setData({
      downTime,
      downSec
    })

    setTimeout(this.countDown, 1000);
  },
  calDownTime: function(downSec, fm) {
    var min = parseInt(downSec / 60);
    var sec = parseInt(downSec - (min * 60));
    var downTime = (min >= 10 ? min : ('0' + min)) + ':' + (sec >= 10 ? sec : ('0' + sec));
    return fm ? (min + '分' + sec + '秒') : downTime;
  },
  doSubmitTest: function() {
    var obj = this.data.obj;

    var api = '/jxq/submitTest';
    var that = this;

    var param = {};
    param.id = obj.id;
    param.rightCount = this.data.rightCount;
    param.wrongCount = this.data.wrongCount;
    param.score = this.data.rightCount;

    var list = this.data.list;
    var items = [];
    for (var i = 0; i < list.length; i++) {
      var item = list[i];
      items.push({
        id: item.jxQTestId,
        answer: item.answer
      })
    }

    param.itemStr = JSON.stringify(items);

    // toast.showLoading();
    req(api, param).then(res => {
      // console.log(res);
      if (res.success) {


      } else {
        toast.show(res.errorMsg);
      }
    });
  },
  viewResult: function() {
    var list = this.data.list;
    for (var i = 0; i < list.length; i++) {
      var item = list[i];
      item.showResult = true;
    }

    this.setData({
      list,
      curIndex: 0,
      inTest: false,
      downTime: this.data.rightCount + '分'
    })
    this.setCur();
  },
  submitM: function() {
    var cur = this.data.cur;
    if (cur.type != 3) {
      return;
    }
    if (cur.showResult) {
      return toast.show('请勿重复提交');
    }

    cur = this.setM(cur);
    if (cur.ma == '') {
      cur.showResult = false;
      return toast.show('至少选择一个选项');
    }

    var rightCount = this.data.rightCount;
    var wrongCount = this.data.wrongCount;
    if (cur.right) {
      rightCount = rightCount + 1;
    } else {
      wrongCount = wrongCount + 1;
    }

    var list = this.data.list;
    list[this.data.curIndex] = cur;

    this.setData({
      cur,
      list,
      rightCount,
      wrongCount,
      showTip: true
    })

    this.addRecord(cur.id, cur.ma);
  },
  subMs: function() {
    var list = this.data.list;
    var rightCount = this.data.rightCount;
    var wrongCount = this.data.wrongCount;
    for (var i = 0; i < list.length; i++) {
      var item = list[i];

      if (item.type == 3) {
        this.setM(item);

        if (item.right) {
          rightCount = rightCount + 1;
        } else {
          wrongCount = wrongCount + 1;
        }

        this.addRecord(item.id, item.ma);
      }
    }

    this.setData({
      list,
      rightCount,
      wrongCount
    });
  },
  setM: function(cur) {
    cur.showResult = true;
    var tans = [];
    var answertrue = cur.answertrue + '';
    for (var i = 0; i < answertrue.length; i++) {
      tans.push(parseInt(answertrue.substring(i, i + 1)));
    }

    var ma = '';
    var ans = cur.ans;
    var tc = 0;
    for (var i = 0; i < ans.length; i++) {
      var an = ans[i];
      if (an.select) {
        an.showResult = true;
        an.right = false;
        ma += (i + 1);
      }

      for (var j = 0; j < tans.length; j++) {
        if (i + 1 == tans[j]) {
          an.right = true;
          an.showResult = true;

          if (an.select) {
            tc++;
          }
        }
      }
    }

    if (tc < tans.length) {
      cur.right = false;
    } else {
      cur.right = true;
    }

    cur.ma = ma;
    return cur;
  }
})